package com.tbit.uqbike.webmanager.controller;


import com.github.pagehelper.PageInfo;
import com.tbit.common.enums.OperaPswEnum;
import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.uqbike.constant.UserConstants;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.object.pojo.Menu;
import com.tbit.uqbike.object.pojo.Role;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.MenuService;
import com.tbit.uqbike.service.business.OperaPswService;
import com.tbit.uqbike.service.business.RoleService;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.RequestContext;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 菜单信息
 *
 * @author jing
 */
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @Resource
    private OperaPswService operaPswService;


    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public JsonResult list(Menu menu) {
        LoginInfo login = getLogin(ServletUtils.getRequest());
        List<Menu> menus = menuService.selectMenuList(menu, login.getAccountUserId());
        return JsonResult.ok(menus, (int) new PageInfo<>(menus).getTotal());
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public JsonResult getInfo(@PathVariable Integer menuId) {
        return JsonResult.ok(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public JsonResult treeselect(Menu menu) {
        LoginInfo login = getLogin(ServletUtils.getRequest());
        List<Menu> menus = menuService.selectMenuList(menu, login.getAccountUserId());
        return JsonResult.ok(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleValue}")
    public JsonResult roleMenuTreeselect(@PathVariable("roleValue") Integer roleValue) {
        LoginInfo login = getLogin(ServletUtils.getRequest());
        List<Menu> pcMenus = menuService.selectMenuList(login.getAccountUserId(), UserConstants.PC_TYPE);
        List<Menu> mainMenus = menuService.selectMenuList(login.getAccountUserId(), UserConstants.MAIN_TYPE);
        Map<String, Object> ajax = new HashMap<>(8);
        List<Role> roles = roleService.selectRoleList(new Role(String.valueOf(roleValue)));
        Map<String, Role> map = new HashMap<>();
        for (Role role : roles) {
            map.put(role.getRoleValue(), role);
        }
        Role role = map.get(roleValue.toString());
        Integer roleId = role.getRoleId();
        List<Integer> checkedKeys = menuService.selectMenuListByRoleId(roleId);
        ajax.put("checkedKeys", checkedKeys);
        ajax.put("pc", menuService.buildMenuTreeSelect(pcMenus));
        ajax.put("main", menuService.buildMenuTreeSelect(mainMenus));
        return JsonResult.ok(ajax);
    }

    /**
     * 加载对应角色权限字符串列表
     *
     * @param roleValue
     * @return
     */
    @GetMapping(value = "/roleMenuSelect/{roleValue}")
    public Result<List<String>> roleMenuSelect(@PathVariable("roleValue") Integer roleValue) {
        List<String> list = new LinkedList<>();
        LoginInfo login = getLogin(ServletUtils.getRequest());
        List<Menu> pcMenus = menuService.selectMenuList(login.getAccountUserId(), UserConstants.PC_TYPE);
        List<Menu> mainMenus = menuService.selectMenuList(login.getAccountUserId(), UserConstants.MAIN_TYPE);
        for (Menu pcMenu : pcMenus) {
            String perms = pcMenu.getPerms();
            if (StringUtils.isNotEmpty(perms)) {
                list.add(perms);
            }
        }
        for (Menu mainMenu : mainMenus) {
            String perms = mainMenu.getPerms();
            if (StringUtils.isNotEmpty(perms)) {
                list.add(perms);
            }
        }
        return Result.success(list);
    }

    /**
     * 新增菜单
     */
    @PostMapping
    @OperateLog(module = ModuleEnum.ROLE, methods = MethodEnum.MENU_ADD)
    public JsonResult add(@Validated @RequestBody Menu menu, HttpServletRequest request) {
        if (!BaseController.getLogin(request).roleIsAdmin()) {
            return JsonResult.fail("仅允许超级管理员操作", TraceUtil.getTraceIdByLocal());
        }
        RequestContext context = getLogin(ServletUtils.getRequest()).context;
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return JsonResult.fail(context.getMessage("insert_menu_name_exists"),TraceUtil.getTraceIdByLocal());
        }
        return JsonResult.toAjax(menuService.insertMenu(menu), context);
    }

    /**
     * 修改菜单
     */
    @PutMapping
    @OperateLog(module = ModuleEnum.ROLE, methods = MethodEnum.MENU_EDIT)
    public JsonResult edit(@Validated @RequestBody Menu menu, HttpServletRequest request) {
        if (!BaseController.getLogin(request).roleIsAdmin()) {
            return JsonResult.fail("仅允许超级管理员操作",TraceUtil.getTraceIdByLocal());
        }

        operaPswService.checkOperaPsw(getLogin(request), OperaPswEnum.OPERA_PSW_SYSTEM_CONFIG.getModule(), menu.getOperaPsw());
        RequestContext context = getLogin(ServletUtils.getRequest()).context;
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return JsonResult.fail(context.getMessage("update_menu_name_exists"),TraceUtil.getTraceIdByLocal());
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return JsonResult.fail(context.getMessage("update_menu_parentId_exists"),TraceUtil.getTraceIdByLocal());
        }
        return JsonResult.toAjax(menuService.updateMenu(menu), context);
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{menuId}")
    @OperateLog(module = ModuleEnum.ROLE, methods = MethodEnum.MENU_DEL)
    public JsonResult remove(@PathVariable("menuId") Integer menuId, HttpServletRequest request) {
        if (!BaseController.getLogin(request).roleIsAdmin()) {
            return JsonResult.fail("仅允许超级管理员操作",TraceUtil.getTraceIdByLocal());
        }
        RequestContext context = getLogin(ServletUtils.getRequest()).context;
        if (menuService.hasChildByMenuId(menuId)) {
            return JsonResult.fail(context.getMessage("delete_menu_exists_child"),TraceUtil.getTraceIdByLocal());
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return JsonResult.fail(context.getMessage("delete_menu_assigned"),TraceUtil.getTraceIdByLocal());
        }
        return JsonResult.toAjax(menuService.deleteMenuById(menuId), context);
    }
}